﻿using System;
using System.Threading.Tasks;
using Loong.Dependency;
using Loong.Json;

namespace Loong.BackgroundJobs
{
    public class BackgroundJobManager : IBackgroundJobManager, ISingletonDependency
    {
        private readonly IBackgroundJobStore _store;

        public BackgroundJobManager(IBackgroundJobStore store)
        {
            _store = store;
        }

        public async Task<string> EnqueueAsync<TJob, TArgs>(TArgs args, string cron = null, DateTime? endTryTime = null, TimeSpan? delay = null, BackgroundJobPriority priority = BackgroundJobPriority.Normal)
            where TJob : IBackgroundJob<TArgs>
        {
            var jobInfo = new BackgroundJobInfo
            {
                JobType = typeof(TJob).AssemblyQualifiedName,
                JobArgs = args.ToJsonString(),
                Cron = cron,
                Priority = priority
            };

            if (endTryTime.HasValue)
            {
                jobInfo.EndTryTime = endTryTime.Value;
            }

            if (delay.HasValue)
            {
                jobInfo.NextTryTime = DateTime.Now.Add(delay.Value);
            }

            await _store.InsertJobAsync(jobInfo);

            return jobInfo.Id.ToString();
        }

        public async Task<bool> DeleteAsync(string jobId)
        {
            if (long.TryParse(jobId, out long finalJobId) == false)
            {
                throw new ArgumentException($"The jobId '{jobId}' should be a number.", nameof(jobId));
            }

            await _store.DeleteJobAsync(finalJobId);

            return true;
        }
    }
}
